<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.keyword" clearable placeholder="渠道名称或渠道号" style="width: 200px;"
                class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search"
                 @click="handleFilter">
        搜 索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary"
                 icon="el-icon-edit" @click="handleCreate">
        新 增
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="id" prop="id" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" prop="createdAt" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createdAt }}</span>
        </template>
      </el-table-column>
      <el-table-column label="渠道商" prop="channelName" align="center">
        <template slot-scope="{row}">
          <span>{{ row.channelName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="渠道号" prop="itemName" align="center">
        <template slot-scope="{row}">
          <span>{{ row.itemName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="渠道编码" prop="code" align="center">
        <template slot-scope="{row}">
          <span>{{ row.code }}</span>
        </template>
      </el-table-column>
      <el-table-column label="H5路径" prop="url" align="center">
        <template slot-scope="{row}">
          <span>{{ row.url }}</span>
        </template>
      </el-table-column>
      <el-table-column label="进量时间" prop="inputTime" align="center">
        <template slot-scope="{row}">
          <span>{{ row.inputStart}} - {{ row.inputEnd }}</span>
        </template>
      </el-table-column>
      <el-table-column label="扣量比例" prop="discountRate" align="center">
        <template slot-scope="{row}">
          <span>{{ row.discountRate }}%</span>
          <el-popover
                  placement="top"
                  width="200">
            <el-slider
                    v-model="row.discountRate"
                    :min=0
                    :max=100
                    @change="changeDiscountRate(row)">
            </el-slider>
            <i class="el-icon-edit" slot="reference"></i>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="进量状态" prop="inputState" align="center">
        <template slot-scope="{row}">
          <span>{{ row.inputState | getStatus(row.inputState)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="扣量开关" prop="inputState" align="center">
        <template slot-scope="{row}">
          <el-switch
            @change="changeState(row)"
            v-model="row.inputState"
            active-color="#13ce66"
            inactive-color="#ddd">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="uv单价" prop="uvPrice" align="center">
        <template slot-scope="{row}">
          <span>{{ row.uvPrice}}</span>
        </template>
      </el-table-column>
      <el-table-column label="注册单价" prop="regPrice" align="center">
        <template slot-scope="{row}">
          <span>{{ row.regPrice}}</span>
        </template>
      </el-table-column>


      <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编 辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删 除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="canalItem" label-position="left" label-width="80px" style="width: 400px; margin-left:50px;">

        <el-form-item label="渠道商" prop="channelId">
          <el-select  v-model="canalItem.channelId"
                     :disabled="dialogStatus!=='新增'"
                     clearable
                     filterable
                     remote
                     reserve-keyword
                     placeholder="请输入关键词"
                     :remote-method="remoteChannelList"
                     :loading="loading"
          >
            <el-option
                    v-for="item in channels"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="渠道号" prop="name">
          <el-input v-model="canalItem.name" />
        </el-form-item>

        <el-form-item label="apkUrl" prop="apkUrl">
          <el-upload
                  class="upload-apk"
                  :action="uploadUrl"
                  :headers="headers"
                  :before-upload="beforeUpload"
                  :on-preview="handleDownload"
                  :before-remove="beforeRemove"
                  :on-remove="handleRemove"
                  :on-exceed="handleExceed"
                  :on-success="handleSuccess"
                  :file-list="fileList">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传apk文件，且不超过10M</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="uv单价" prop="uvPrice">
          <el-input v-model="canalItem.uvPrice" />
        </el-form-item>

        <el-form-item label="注册单价" prop="regPrice">
          <el-input v-model="canalItem.regPrice" />
        </el-form-item>

        <el-form-item label="进量时间" prop="inputTime">
          <el-time-picker
            is-range
            value-format="HH:mm:ss"
            v-model="canalItem.inputTime"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围">
          </el-time-picker>
        </el-form-item>

        <el-form-item label="进量折扣" prop="discountRate">
          <el-slider
            v-model="canalItem.discountRate"
            :min=0
            :max=100>
          </el-slider>
        </el-form-item>

        <el-form-item label="进量状态" prop="inputState">
          <el-switch
            v-model="canalItem.discountState"
            active-color="#13ce66"
            inactive-color="#aaa">
          </el-switch>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='新增'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="删除" :visible.sync="dialogDelVisible">
      <p>是否删除该渠道号？</p>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDelVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="deleteChannel()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import Vue from 'vue'
  import { fetchList, canalList, createCanalItem, detail, updateCanalItem, setDiscountState, deleteItem, changeRate } from '@/api/canal/canalItem'
  import Pagination from '@/components/Pagination'
  import waves from '@/directive/waves'
  import store from '@/store'

  export default {
    name: 'CanalItem',
    components: { Pagination },
    directives: { waves },

    data() {
      return {
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          pageNo: 1,
          pageSize: 20,
          keyword: ''
        },
        loading: false,
        channels:[],
        canalItem: {
          id: null,
          channelId: null,
          name: null,
          apkUrl: null,
          uvPrice: null,
          regPrice: null,
          inputTime: [ '00:00:00', '23:59:59' ],
          discountRate: 50,
          discountState: true
        },
        uploadUrl: Vue.prototype.APIHOST + "/channel/item/apk/upload",
        fileList:[],
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '新增'
        },
        rules: {
          channelId: [{ required: true, message: '渠道商不能为空', trigger: 'blur'}],
          name: [{ required: true, message: '渠道号名称不能为空', trigger: 'blur'}],
          apkUrl: [{ required: true, message: '请上传apk', trigger: 'blur' }],
          uvPrice: [{ required: true, message: 'uv单价不能为空', trigger: 'blur' }],
          regPrice: [{ required: true, message: '注册单价不能为空', trigger: 'blur' }],
          inputTime: [{ required: true, message: '进量时间不能为空', trigger: 'blur' }],
        },
        dialogDelVisible: false,
        wellDel: undefined
      }
    },
    created() {
      const that = this
      that.getList()
      that.remoteChannelList('')
    },
    computed: {
      headers() {
        return {
          'Access-Token': store.getters.token
        }
      }
    },
    filters: {
      getStatus(state) {
        switch (state) {
          case false : return '暂停中'
          case true : return '进量中'
        }
      }
    },
    methods: {
      getList() {
        const that = this
        that.listLoading = true
        const { keyword, pageNo, pageSize } = that.listQuery
        fetchList({ keyword: keyword, pageNo: pageNo, pageSize: pageSize }).then(response => {
          that.list = response.data.dataList
          that.total = response.data.total
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },
      remoteChannelList(query) {
        this.loading = true
        canalList({ keyword: query }).then(response => {
          if(response.code === 200) {
            this.loading = false
            this.channels = response.data;
          }
        });
      },
      handleFilter() {
        const that = this
        that.listQuery.pageNo = 1
        that.getList()
      },
      resetCanal() {
        this.canalItem = {
          id: null,
          channelId: null,
          name: null,
          apkUrl: null,
          uvPrice: null,
          regPrice: null,
          inputTime: [ '00:00:00', '23:59:59' ],
          discountRate: 50,
          discountState: true
        }
        this.fileList = []
      },
      handleCreate() {
        this.resetCanal()
        this.dialogStatus = '新增'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleUpdate(row) {
        const that = this
        that.resetCanal()
        detail(row.id).then(response => {
          if (response.code === 200) {
            const { id, channelId, name, apkUrl, uvPrice, regPrice, inputStart, inputEnd, discountRate, discountState } = response.data
            that.canalItem.id = id
            that.canalItem.channelId = channelId
            that.canalItem.name = name
            that.canalItem.apkUrl = apkUrl
            that.canalItem.uvPrice = uvPrice
            that.canalItem.regPrice = regPrice
            that.canalItem.inputTime = [  inputStart, inputEnd ]
            that.canalItem.discountRate = discountRate
            that.canalItem.discountState = discountState
            const urlArr = apkUrl.split('/')
            that.fileList = [ { name: urlArr[urlArr.length - 1], url: apkUrl } ]
          }
        })
        this.dialogStatus = '编辑'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const { channelId, name, apkUrl, uvPrice, regPrice, discountRate, discountState  } = this.canalItem
            const requestBody = {
              channelId: channelId, name: name, apkUrl: apkUrl,
              uvPrice: uvPrice, regPrice: regPrice, inputStart: this.canalItem.inputTime[0],
              inputEnd: this.canalItem.inputTime[1], discountRate: discountRate, discountState: discountState
            }
            createCanalItem(requestBody).then((response) => {
              if (response.code !== 200) {
                this.$notify({
                  title: '失败',
                  message: response.message,
                  type: 'fail',
                  duration: 2000
                })
              } else {
                this.dialogFormVisible = false
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
                this.getList()
              }
            })
          }
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const { id, channelId, name, apkUrl, uvPrice, regPrice, discountRate, discountState  } = this.canalItem
            const requestBody = {
              id: id, channelId: channelId, name: name, apkUrl: apkUrl,
              uvPrice: uvPrice, regPrice: regPrice, inputStart: this.canalItem.inputTime[0],
              inputEnd: this.canalItem.inputTime[1], discountRate: discountRate, discountState: discountState
            }
            updateCanalItem(requestBody).then((response) => {
              if (response.code !== 200) {
                this.$notify({
                  title: '失败',
                  message: response.message,
                  type: 'fail',
                  duration: 2000
                })
              } else {
                this.dialogFormVisible = false
                this.$notify({
                  title: '成功',
                  message: '修改成功',
                  type: 'success',
                  duration: 2000
                })
                this.getList()
              }
            })
          }
        })
      },

      handleDelete(row) {
        this.dialogDelVisible = true
        this.wellDel = row.id
      },
      deleteChannel() {
        deleteItem([ this.wellDel ]).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.dialogDelVisible = false
            this.getList()
          } else {
            this.$notify({
              title: '失败',
              message: response.message,
              type: 'fail',
              duration: 2000
            })
            this.dialogDelVisible = false
          }
        })
      },
      handleReset(row) {
        resetPwd(row.id).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '密码重置成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '失败',
              message: response.message,
              type: 'fail',
              duration: 2000
            })
          }
        })
      },
      beforeUpload (file,fileList) {
        let isAPK = file.type === "application/vnd.android.package-archive";
        let isLt10M = file.size / 1024 / 1024 < 10;
        if (!isAPK) {
          this.$message.error('上传文件格式错误!!');
        }
        if (!isLt10M) {
          this.$message.error('上传apk大小不能超过 10MB!');
        }
        return isAPK && isLt10M;
      },
      handleExceed(files,fileList) {
        this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      beforeRemove(file) {
        return this.$confirm(`确定移除 ${ file.name }？`);
      },
      handleRemove(file, fileList) {
        for (let i = 0; i < fileList.length; i++) {
          if (fileList[i].name === file.name) {
            fileList.splice(i,1);
          }
        }
      },
      handleDownload() {
        location.href = this.canalItem.apkUrl;
      },
      handleSuccess(response,file) {
        const that = this;
        that.canalItem.apkUrl = response.data;
        file.url = response.data;
      },
      changeState(row) {
        setDiscountState(row.id).then(response => {
          if (response.code !== 200) {
            this.$notify({
              title: '失败',
              message: response.message,
              type: 'fail',
              duration: 2000
            })
          }
        })
      },
      changeDiscountRate(row) {
        changeRate({ id: row.id, rate: row.discountRate })
      }
    }
  }
</script>

<style scoped>

</style>

